package com.channel.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.channel.modules.system.domain.Dept;
import com.channel.modules.system.domain.User;
import com.channel.modules.system.domain.vo.UserPassVo;
import com.channel.modules.system.service.DataService;
import com.channel.modules.system.service.DeptService;
import com.channel.modules.system.service.RoleService;
import com.channel.modules.system.service.UserService;
import com.channel.modules.system.service.dto.RoleSmallDto;
import com.channel.modules.system.service.dto.UserDto;
import com.channel.modules.system.service.dto.UserQueryCriteria;
import com.commons.config.RsaProperties;
import com.commons.exception.BadRequestException;
import com.commons.utils.PageResult;
import com.commons.utils.PageUtil;
import com.commons.utils.RsaUtils;
import com.commons.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final PasswordEncoder passwordEncoder;
    private final UserService userService;
    private final DataService dataService;
    private final DeptService deptService;
    private final RoleService roleService;

    @Autowired
    public UserController(PasswordEncoder passwordEncoder, UserService userService, DataService dataService, DeptService deptService, RoleService roleService) {
        this.passwordEncoder = passwordEncoder;
        this.userService = userService;
        this.dataService = dataService;
        this.deptService = deptService;
        this.roleService = roleService;
    }
    //导出用户数据
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('user:list')")
    public void exportUser(HttpServletResponse response, UserQueryCriteria criteria) throws IOException{
        userService.download(userService.queryAll(criteria),response);
    }

    //查询用户
    @GetMapping
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<PageResult<UserDto>> queryUser(UserQueryCriteria criteria, Pageable pageable){
        if(!ObjectUtil.isEmpty(criteria.getDeptId())){
            criteria.getDeptIds().add(criteria.getDeptId());
            //先查找是否存在子节点
            List<Dept> data = deptService.findByPid(criteria.getDeptId());
            //然后把子节点的ID都放到集合中
            criteria.getDeptIds().addAll(deptService.getDeptChildren(data));
        }
        //获取数据权限
        List<Long> Scopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUserName()));
        //criteria.getDeptIds() 不为空并且数据权限不为空则取交集
        if(!CollectionUtil.isEmpty(criteria.getDeptIds())&&!CollectionUtil.isEmpty(Scopes)){
            //取交集
            criteria.getDeptIds().retainAll(Scopes);
            if(!CollectionUtil.isEmpty(criteria.getDeptIds())){
                return new ResponseEntity<>(userService.queryAll(criteria,pageable), HttpStatus.OK);
            }
        }else {
            //否则取并集
            criteria.getDeptIds().addAll(Scopes);
            return new ResponseEntity<>(userService.queryAll(criteria,pageable), HttpStatus.OK);
        }
        return new ResponseEntity<>(PageUtil.noData(),HttpStatus.OK);
    }

    //新增用户
    @PostMapping
    @PreAuthorize("@el.check('user:add')")
    public ResponseEntity<Object> createUser(@Validated @RequestBody User resources){
        checkLevel(resources);
        //默认密码123456
        resources.setPassword(passwordEncoder.encode("123456"));
        userService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    //修改用户
    @PutMapping
    @PreAuthorize("el.check('user:edit')")
    public ResponseEntity<Object> updateUser(@Validated(User.Update.class) @RequestBody User resources) throws Exception{
        checkLevel(resources);
        userService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    //修改用户，个人中心
    @PutMapping(value = "center")
    public ResponseEntity<Object> centerUser(@Validated(User.Update.class) @RequestBody User resources){
        if(!resources.getId().equals(SecurityUtils.getCurrentUserId())){
            throw new BadRequestException("不能修改他人资料");
        }
        userService.updateCenter(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    //删除用户
    @DeleteMapping
    @PreAuthorize("@el.check('user:del')")
    public ResponseEntity<Object> deleteUser(@RequestBody Set<Long> ids){
        for (Long id : ids){
           Integer currentLevel= Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
           Integer optLevel=Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
           if(currentLevel>optLevel){
               throw new BadRequestException("角色权限不足，不能删除"+userService.findById(id).getUsername());
           }

        }
        userService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    //修改密码
    @PostMapping("/updatePass")
    public ResponseEntity<Object> updatePass(@RequestBody UserPassVo passVo) throws Exception{
        String oldPass=RsaUtils.decryptByPrivateKey(RsaProperties.priavteKey, passVo.getOldPass());
        String newPass=RsaUtils.decryptByPrivateKey(RsaProperties.priavteKey, passVo.getNewPass());
        UserDto user = userService.findByName(SecurityUtils.getCurrentUserName());
        if(!passwordEncoder.matches(oldPass,user.getPassword())){
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if(passwordEncoder.matches(newPass,user.getPassword())){
            throw new BadRequestException("新密码不能和旧密码相同");
        }
        userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    //重置密码
    public ResponseEntity<Object> resetPwd(@RequestBody Set<Long> ids){
        String pwd = passwordEncoder.encode("123456");
        userService.resetPwd(ids,pwd);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 如果当前用户的角色级别低于创建用户的角色级别，则抛出权限不足的错误
     */
    private void checkLevel(User resources){
        Integer currentLevel=Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        Integer optLevel=roleService.findByRoles(resources.getRoles());
        if(currentLevel>optLevel){
            throw new BadRequestException("角色权限不足!");
        }
    }

}
